package com.zhss.ddd.lottery.draw.core.entity;

import com.zhss.ddd.lottery.draw.activity.api.ILotteryDrawActivity;
import com.zhss.ddd.lottery.draw.activity.api.LotteryDrawActivityRef;
import com.zhss.ddd.lottery.draw.activity.vo.DrawLotteryContext;
import com.zhss.ddd.lottery.draw.activity.vo.WinPrize;
import com.zhss.ddd.lottery.draw.core.spring.SpringContext;
import com.zhss.ddd.lottery.draw.risk.control.api.IRiskControlAlgorithm;
import com.zhss.ddd.lottery.draw.risk.control.api.RiskControlAlgorithmRef;
import com.zhss.ddd.lottery.draw.risk.control.api.RiskControlApi;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

/**
 * 抽奖行为
 */
@Data
@Scope("prototype")
public class DrawLottery {

    /**
     * 一次抽奖行为的标识符
     */
    private Long id;
    /**
     * 进行抽奖的用户id
     */
    private Long userId;
    /**
     * 抽奖活动id
     */
    private Long lotteryDrawActivityId;

    @Autowired
    private SpringContext springContext;


    /**
     * 执行本次抽奖 屏蔽掉底层RPC的细节
     */
    public String execute() {
        // 先进行风控，判断用户是否可以进行抽奖
        RiskControlAlgorithmRef riskControlAlgorithmRef = springContext.getBean(RiskControlAlgorithmRef.class);
        riskControlAlgorithmRef.setUserId(userId);
        System.out.println("调用风控算法实体的行为......");
        // 底层去执行RPC
        Boolean rickControlResult = riskControlAlgorithmRef.intercept();
        if(!rickControlResult) {
            return "风控拦截，用户有风险行为，不允许执行抽奖";
        }

        // 获取抽奖活动（远程实体）
        LotteryDrawActivityRef lotteryDrawActivityRef = springContext.getBean(LotteryDrawActivityRef.class);
        lotteryDrawActivityRef.setId(lotteryDrawActivityId);
        DrawLotteryContext drawLotteryContext = lotteryDrawActivityRef.getContext();
        System.out.println("获取到了抽奖的上下文");

        // 使用抽奖算法进行抽奖（本地实体）
        DrawLotteryAlgorithm drawLotteryAlgorithm = springContext.getBean(DrawLotteryAlgorithm.class);
        drawLotteryAlgorithm.setDrawLotteryContext(drawLotteryContext);
        System.out.println("调用抽奖算法实体的行为......");
        // 底层去执行RPC
        WinPrize prize = drawLotteryAlgorithm.execute();
        return "抽奖成功，奖品为：" + prize;
    }

}
